//
//  UserSetingVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/18.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "UserSetingVC.h"
#import "UserSetingShowTableViewCell.h"
#import "LoginVC.h"
#import "BaseNavigationController.h"
#import "UserSetingExitTableViewCell.h"
#import "ServiceInfoVC.h"
#import "ContactServiceVC.h"
#import "AboutWeVC.h"
#import "JQScanViewController.h"
#import "FuWuWebVC.h"
#import "ChangePasswordVC.h"

@interface UserSetingVC ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic,strong) NSArray *titleArrays;
@end

@implementation UserSetingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置";
    [self setUi];

    
}

- (void)setUi {
    
    [self.view addSubview:self.tableView];
    
    self.titleArrays = @[@"清空缓存",@"服务条款",@"修改密码",@"关于我们",@"联系客服",@"退出会员"];
//    self.titleArrays = @[@"清空缓存",@"服务条款",@"修改密码"];
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight= 0;
        self.tableView.contentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
    }
    
}


- (UITableView *)tableView {
    if (!_tableView) {
        CGRect frame = CGRectMake(0.0f, NavBarHeight, kScreenW, kScreenH - NavBarHeight);
        UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
            // 设置tableView的headView
        tableView.tableHeaderView = [UIView new];
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle = NO;
        tableView.delegate = self;
        tableView.dataSource = self;
        // 设置tableView的sectionHeadHeight为segmentViewHeight
        tableView.showsVerticalScrollIndicator = false;
        [tableView registerNib:[UINib nibWithNibName:@"UserSetingShowTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserSetingShowTableViewCell"];
        [tableView registerNib:[UINib nibWithNibName:@"UserSetingExitTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserSetingExitTableViewCell"];
        
        
        _tableView = tableView;
        _tableView.backgroundColor  = VCBgcolor;
        
    }
    
    return _tableView;
}


#pragma mark- UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"kUserIsMerchants"] && [[NSUserDefaults standardUserDefaults] boolForKey:kisLogin])  {
            return self.titleArrays.count - 1;

        }else {
            return self.titleArrays.count;

        }
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        UserSetingShowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserSetingShowTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = self.titleArrays[indexPath.row];
        cell.clearLabel.text = [NSString stringWithFormat:@"%.2fM",[self filePath]];
        tableView.rowHeight = 50;
        if (indexPath.row == 0) {
            [cell.clearLabel setHidden:NO];
        }else {
            [cell.clearLabel setHidden:YES];
        }
        return cell;
        
    }else {
            
        UserSetingExitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserSetingExitTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        tableView.rowHeight = 50;
        
        return cell;
        
    }
    
    
}


#pragma mark - section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.0000001;
}


#pragma mark - section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *view= [[UIView alloc]initWithFrame:CGRectMake( 0, 0, KSCREEN_WIDTH, 0.00001)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

#pragma mark - section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        
        return 10;
    }
    return 0.0001;
}

#pragma mark - section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, KSCREEN_WIDTH, 0)];
    view.backgroundColor = VCBgcolor;
    return view;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        switch (indexPath.row) {
            case 0:
            {
                [self clearMemoryPrompt];
            }
                break;
            case 1: {
//                ServiceInfoVC *vc = [[ServiceInfoVC alloc]init];
//                [self.navigationController pushViewController:vc animated:YES];
                FuWuWebVC *vc = [[FuWuWebVC alloc]init];
                vc.title = @"服务条款";
                vc.linkPath = [[NSBundle mainBundle] pathForResource:@"服务条款-更新.docx" ofType:nil];
                [self.navigationController pushViewController:vc animated:YES];
                }
                break;
            case 2:
            {
                [self changePassword];
            }
                break;
            case 3:
            {
                AboutWeVC *vc = [[AboutWeVC alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
            case 4:
            {
               ContactServiceVC *vc = [[ContactServiceVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
            }
               break;
            case 5:
            {
              [self exitVip];
            }
              break;
            default:
                break;
        }
        
    }else {
        
        [self popAlert];
        
    }
    
    
}

- (void)exitVip {
    
    // 系统提示框
       UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否联系客服退出会员？" preferredStyle:UIAlertControllerStyleAlert];
       
       [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           
       }]];
       
       [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
           [CommonTTool serviceCallPhone];
           
       }]];
       
       [self presentViewController:alterController animated:YES completion:nil];
       
    
}


- (void)contactService {
    
    
}
                                

                                
#pragma mark - 清空缓存提示框
- (void)clearMemoryPrompt {
    NSString *message = @"是否确定清空缓存？";
    NSString *okButtonTitle = @"确定";
    NSString *cancelStr = @"取消";
    // 初始化
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    // 创建操作
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:okButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                               {
                                   // 操作具体内容
                                   [self clearMemory];
                               }];
    // 添加操作
    [alertController addAction:okAction];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancleAction];
    // 呈现警告视图
    [self presentViewController:alertController animated:YES completion:nil];
    
    //修改message
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:message];
    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:kAColor(0, 0.7) range:NSMakeRange(0, message.length)];
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:kPRFont(16) range:NSMakeRange(0, message.length)];
    [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
}

#pragma mark - 清除缓存事件
- (void)clearMemory {
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    
    for (NSString *p in files) {
        NSError *error = nil ;
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
}

- (void)clearCachSuccess {
    [self.tableView reloadData]; // 清理完之后重新导入数据
}

#pragma mark -显示缓存大小
- (float)filePath {
    NSString *cachPath = [ NSSearchPathForDirectoriesInDomains( NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [self folderSizeAtPath:cachPath];
}

#pragma mark - 2: 遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）
- (float)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString *fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    return folderSize / (1024.0 * 1024.0);
}


- (long long)fileSizeAtPath:(NSString *)filePath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath :filePath]) {
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}


#pragma mark - 退出APP
- (void)exitApp {
    
     // 清空所有本地存储数据
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserInfo];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserMerchantsInfo];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kisLogin];
    [[NSNotificationCenter defaultCenter] postNotificationName:kUserInfoDetailsExitUpDate object:nil];
    [LEUserManager deleteToken];

    LoginVC *loginVC = [[LoginVC alloc] init];
    
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
    
}

- (void)popAlert {
    __weak typeof(self) weakSelf = self;
    // 系统提示框
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否退出登录？" preferredStyle:UIAlertControllerStyleAlert];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf exitApp];
        
    }]];
    
    [self presentViewController:alterController animated:YES completion:nil];
    
}


- (void)changePassword {
    
    ChangePasswordVC *vc  = [[ChangePasswordVC alloc]initWithNibName:@"ChangePasswordVC" bundle:nil];
    
    [self.navigationController pushViewController:vc animated:YES];
    
       
    
}




@end
